package twelve;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.net.URL;
import java.util.List;

public class TestScriptEngineManager {
    public static void main(String[] args) throws Exception{
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        engine.put("msg", "gaoqi is a good man!");
        String str = "var user = { name:'gaoqi', age:18, schools:['清华大学','北京尚学堂'] };";
        str += "print(user.name);";

        engine.eval(str);
        System.out.println(engine.get("msg"));
        engine.eval("msg = 'sxt is a good school';");

        System.out.println(engine.get("msg"));
        System.out.println("############################");

        engine.eval("function add(a,b){var sum = a + b; return sum;}");
        Invocable jsInvoke = (Invocable)engine;
        Object result1 = jsInvoke.invokeFunction("add", new Object[]{13,20});
        System.out.println(result1);

        //导入其它java包，使用其它包中的java类
        //注：本例所用的环境java8已不支持Rhino，已改为Nashorn。添加脚本：load(\"nashorn:mozilla_compat.js\"); 运行
        String jsCode = "load(\"nashorn:mozilla_compat.js\"); importPackage(java.util); var list = Arrays.asList([\"北大\",\"清华\",\"复旦\"]);";

        engine.eval(jsCode);

        List<String> list2 = (List<String>) engine.get("list");
        for (String temp : list2) {
            System.out.println(temp);
        }

        //执行js文件(a.js放到项目src下)
//        URL url = TestScriptEngineManager.class.getClassLoader().getResource("a.js");
//        FileReader fr = new FileReader("g:/java/test/a.js");//(url.getPath());
//        engine.eval(fr);
//        fr.close();
    }
}
